package com.example.myapplication.tools;

import android.util.Log;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.Objects;

/**
 * @author sjh
 * @Description
 * @create 2022/3/8 9:14
 */
public class RequestTool {

    private static final String TAG = RequestTool.class.getSimpleName();

    /**
     * 同步请求测试，将response输出到console。注意：需要新开线程执行。
     *
     * @param call okhttp的请求call
     * @param log 日志内容
     */
    public static void testRequestCallSync(final Call call, String log) {
        final String finalLog = log == null ? "" : log;
        try {
            Response response = call.execute();
            if (response.isSuccessful()) {
                Log.i(TAG, finalLog + "onResponse: " + Objects.requireNonNull(response.body()).string());
            } else {
                Log.i(TAG, finalLog + "onFailure: " + Objects.requireNonNull(response.body()).string());
            }
        } catch (Exception e) {
            Log.i(TAG, finalLog + "onFailure: " + e.getMessage());
        }
    }

    /**
     * 异步请求测试，将response输出到console。无需新开线程。
     *
     * @param call okhttp的请求call
     * @param log 日志内容
     */
    public static void testRequestCallAsync(Call call, String log) {
        final String finalLog = log == null ? "" : log;
        call.enqueue(new Callback() {

            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.i(TAG, finalLog + "onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                Log.i(TAG, finalLog + "onResponse: " + Objects.requireNonNull(response.body()).string());
            }

        });
    }


}
